<template>
  <div class="order-management">
    <div class="page-header">
      <h1>订单管理</h1>
      <div class="header-actions">
        <el-button 
          type="primary" 
          icon="Export" 
          @click="exportOrders"
          :loading="exportLoading"
        >
          导出订单
        </el-button>
      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <el-card>
        <el-form :model="filterForm" inline class="filter-form">
          <el-form-item label="订单状态">
            <el-select v-model="filterForm.status" placeholder="全部状态" clearable>
              <el-option label="全部状态" value="" />
              <el-option label="未支付" :value="0" />
              <el-option label="已支付" :value="1" />
              <el-option label="已取消" :value="2" />
              <el-option label="已完成" :value="3" />
              <el-option label="已退款" :value="4" />
            </el-select>
          </el-form-item>

          <el-form-item label="预约日期">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleDateRangeChange"
            />
          </el-form-item>

          <el-form-item label="搜索">
            <el-input
              v-model="filterForm.search"
              placeholder="搜索订单号、用户姓名、手机号、场馆名称"
              style="width: 300px"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button icon="Search" @click="handleSearch" />
              </template>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-value">{{ statistics.today_orders || 0 }}</div>
              <div class="stat-label">今日订单</div>
            </div>
            <div class="stat-icon">
              <el-icon><Document /></el-icon>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-value">¥{{ (statistics.total_revenue || 0).toFixed(2) }}</div>
              <div class="stat-label">总收入</div>
            </div>
            <div class="stat-icon">
              <el-icon><Money /></el-icon>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-value">{{ total }}</div>
              <div class="stat-label">总订单数</div>
            </div>
            <div class="stat-icon">
              <el-icon><DataLine /></el-icon>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-value">{{ getCompletedOrdersCount }}</div>
              <div class="stat-label">已完成订单</div>
            </div>
            <div class="stat-icon">
              <el-icon><Check /></el-icon>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 订单列表 -->
    <div class="table-section">
      <el-card>
        <el-table 
          :data="orders" 
          v-loading="loading"
          stripe
          style="width: 100%"
        >
          <el-table-column prop="order_no" label="订单号" width="160" />
          
          <el-table-column label="关联活动" width="180">
            <template #default="{ row }">
              <div v-if="row.activity_id" class="activity-info">
                <el-tag type="primary" size="small">
                  #{{ row.activity_id }}
                </el-tag>
                <div class="activity-title">{{ row.activity_title || '未知活动' }}</div>
              </div>
              <el-tag v-else type="info" size="small">无关联活动</el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="用户信息" width="150">
            <template #default="{ row }">
              <div class="user-info">
                <div class="user-name">{{ row.user?.name || '-' }}</div>
                <div class="user-phone">{{ row.user?.phone || '-' }}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="场馆信息" width="200">
            <template #default="{ row }">
              <div class="venue-info">
                <div class="venue-name">{{ row.venue?.name || '-' }}</div>
                <div class="venue-location">{{ row.venue?.location || '-' }}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="预约时间" width="180">
            <template #default="{ row }">
              <div class="time-info">
                <div class="date">{{ row.reservation_date }}</div>
                <div class="time">{{ row.start_time }} - {{ row.end_time }}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="amount" label="金额" width="100">
            <template #default="{ row }">
              <span class="amount">¥{{ row.amount.toFixed(2) }}</span>
            </template>
          </el-table-column>

          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ row.status_text }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="created_at" label="下单时间" width="160" />

          <el-table-column label="操作" width="220" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="viewOrderDetail(row)"
                >
                  详情
                </el-button>
                <el-button 
                  v-if="row.status === 0"
                  type="success" 
                  size="small" 
                  @click="generatePaymentQR(row)"
                >
                  付款码
                </el-button>
                <el-dropdown @command="(command) => handleAction(command, row)">
                  <el-button type="primary" size="small">
                    更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="changeStatus">修改状态</el-dropdown-item>
                      <el-dropdown-item command="viewUser">查看用户</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="订单详情" 
      width="800px"
    >
      <div v-if="currentOrder" class="order-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ currentOrder.order_no }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(currentOrder.status)">
              {{ currentOrder.status_text }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="用户姓名">{{ currentOrder.user?.name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentOrder.user?.phone || '-' }}</el-descriptions-item>
          <el-descriptions-item label="场馆名称">{{ currentOrder.venue?.name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="场馆地址">{{ currentOrder.venue?.address || '-' }}</el-descriptions-item>
          <el-descriptions-item label="预约日期">{{ currentOrder.reservation_date }}</el-descriptions-item>
          <el-descriptions-item label="预约时间">{{ currentOrder.start_time }} - {{ currentOrder.end_time }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">¥{{ currentOrder.amount.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="下单时间">{{ currentOrder.created_at }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ currentOrder.updated_at }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{ currentOrder.remark || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 修改状态对话框 -->
    <el-dialog 
      v-model="statusDialogVisible" 
      title="修改订单状态" 
      width="400px"
    >
      <el-form :model="statusForm" label-width="80px">
        <el-form-item label="当前状态">
          <el-tag :type="getStatusType(statusForm.currentStatus)">
            {{ getStatusText(statusForm.currentStatus) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新状态" required>
          <el-select v-model="statusForm.newStatus" placeholder="选择新状态">
            <el-option label="未支付" :value="0" />
            <el-option label="已支付" :value="1" />
            <el-option label="已取消" :value="2" />
            <el-option label="已完成" :value="3" />
            <el-option label="已退款" :value="4" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="statusDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmStatusChange"
          :loading="statusLoading"
        >
          确认修改
        </el-button>
      </template>
    </el-dialog>

    <!-- 付款二维码对话框 -->
    <el-dialog 
      v-model="qrCodeDialogVisible" 
      title="支付二维码" 
      width="400px"
      center
    >
      <div class="qr-code-container">
        <div v-if="qrCodeLoading" class="qr-loading">
          <el-icon class="is-loading"><Loading /></el-icon>
          <p>正在生成二维码...</p>
        </div>
        <div v-else-if="qrCodeData" class="qr-content">
          <div class="qr-code">
            <vue-qrcode :value="qrCodeData.qr_code" :options="qrOptions" />
          </div>
          <div class="qr-info">
            <p><strong>订单号：</strong>{{ qrCodeData.order_no }}</p>
            <p><strong>支付金额：</strong>¥{{ qrCodeData.amount.toFixed(2) }}</p>
            <p><strong>场馆：</strong>{{ qrCodeData.venue_name }}</p>
            <p><strong>预约时间：</strong>{{ qrCodeData.reservation_date }} {{ qrCodeData.start_time }}-{{ qrCodeData.end_time }}</p>
            <p class="qr-tip">请使用微信扫码支付</p>
          </div>
        </div>
        <div v-else class="qr-error">
          <p>二维码生成失败，请重试</p>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="qrCodeDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="refreshQRCode" :loading="qrCodeLoading">
          刷新二维码
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, Money, DataLine, Check, ArrowDown, Loading } from '@element-plus/icons-vue'
import VueQrcode from '@chenfengyuan/vue-qrcode'
import axios from 'axios'

// 响应式数据
const loading = ref(false)
const exportLoading = ref(false)
const statusLoading = ref(false)
const orders = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const dateRange = ref([])

// 统计数据
const statistics = ref({
  today_orders: 0,
  total_revenue: 0
})

// 筛选表单
const filterForm = reactive({
  status: '',
  start_date: '',
  end_date: '',
  search: ''
})

// 对话框显示状态
const detailDialogVisible = ref(false)
const statusDialogVisible = ref(false)
const qrCodeDialogVisible = ref(false)
const currentOrder = ref(null)

// 二维码相关数据
const qrCodeLoading = ref(false)
const qrCodeData = ref(null)
const qrOptions = {
  width: 200,
  height: 200,
  margin: 1
}

// 状态修改表单
const statusForm = reactive({
  orderId: null,
  currentStatus: null,
  newStatus: null
})

// 计算属性
const getCompletedOrdersCount = computed(() => {
  return orders.value.filter(order => order.status === 3).length
})

// 页面加载
onMounted(() => {
  fetchOrders()
  fetchStatistics()
})

// 获取订单列表
const fetchOrders = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      per_page: pageSize.value,
      ...filterForm
    }
    
    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await axios.get('/api/v1/admin/orders/simple', { params })
    
    if (response.data.code === 200) {
      orders.value = response.data.data.orders
      total.value = response.data.data.total
    } else {
      ElMessage.error(response.data.message || '获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 获取统计信息
const fetchStatistics = async () => {
  try {
    const response = await axios.get('/api/v1/admin/orders/statistics')
    
    if (response.data.code === 200) {
      statistics.value = response.data.data
    }
  } catch (error) {
    console.error('获取统计信息失败:', error)
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchOrders()
}

// 重置筛选
const resetFilters = () => {
  Object.assign(filterForm, {
    status: '',
    start_date: '',
    end_date: '',
    search: ''
  })
  dateRange.value = []
  currentPage.value = 1
  fetchOrders()
}

// 处理日期范围变化
const handleDateRangeChange = (dates) => {
  if (dates && dates.length === 2) {
    filterForm.start_date = dates[0]
    filterForm.end_date = dates[1]
  } else {
    filterForm.start_date = ''
    filterForm.end_date = ''
  }
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchOrders()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchOrders()
}

// 查看订单详情
const viewOrderDetail = (order) => {
  currentOrder.value = order
  detailDialogVisible.value = true
}

// 处理操作
const handleAction = (command, order) => {
  switch (command) {
    case 'changeStatus':
      showStatusDialog(order)
      break
    case 'viewUser':
      // 跳转到用户详情（待实现）
      ElMessage.info('功能开发中')
      break
  }
}

// 显示状态修改对话框
const showStatusDialog = (order) => {
  statusForm.orderId = order.id
  statusForm.currentStatus = order.status
  statusForm.newStatus = order.status
  statusDialogVisible.value = true
}

// 确认状态修改
const confirmStatusChange = async () => {
  if (statusForm.newStatus === statusForm.currentStatus) {
    ElMessage.warning('状态未发生变化')
    return
  }

  statusLoading.value = true
  try {
    const response = await axios.put(`/api/v1/admin/orders/${statusForm.orderId}/status`, {
      status: statusForm.newStatus
    })
    
    if (response.data.code === 200) {
      ElMessage.success('状态修改成功')
      statusDialogVisible.value = false
      fetchOrders()
    } else {
      ElMessage.error(response.data.message || '状态修改失败')
    }
  } catch (error) {
    console.error('状态修改失败:', error)
    ElMessage.error('状态修改失败')
  } finally {
    statusLoading.value = false
  }
}

// 导出订单
const exportOrders = async () => {
  try {
    await ElMessageBox.confirm('确认导出当前筛选条件下的订单数据？', '确认导出', {
      type: 'warning'
    })

    exportLoading.value = true
    
    const params = { ...filterForm }
    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await axios.get('/api/v1/admin/orders/export', { params })
    
    if (response.data.code === 200) {
      // 这里可以实现实际的导出功能，比如下载CSV文件
      const exportData = response.data.data.orders
      
      // 简单的CSV导出示例
      const csvContent = convertToCSV(exportData)
      downloadCSV(csvContent, 'orders_export.csv')
      
      ElMessage.success(`成功导出 ${exportData.length} 条订单数据`)
    } else {
      ElMessage.error(response.data.message || '导出失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('导出失败:', error)
      ElMessage.error('导出失败')
    }
  } finally {
    exportLoading.value = false
  }
}

// 转换为CSV格式
const convertToCSV = (data) => {
  const headers = ['订单号', '用户姓名', '联系电话', '场馆名称', '预约日期', '预约时间', '金额', '状态', '下单时间']
  const csvRows = [headers.join(',')]
  
  data.forEach(order => {
    const row = [
      order.order_no,
      order.user?.name || '',
      order.user?.phone || '',
      order.venue?.name || '',
      order.reservation_date,
      `${order.start_time}-${order.end_time}`,
      order.amount,
      order.status_text,
      order.created_at
    ]
    csvRows.push(row.join(','))
  })
  
  return csvRows.join('\n')
}

// 下载CSV文件
const downloadCSV = (content, filename) => {
  const blob = new Blob(['\ufeff' + content], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = filename
  link.click()
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    0: 'warning',  // 未支付
    1: 'success',  // 已支付
    2: 'info',     // 已取消
    3: 'success',  // 已完成
    4: 'danger'    // 已退款
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    0: '未支付',
    1: '已支付',
    2: '已取消',
    3: '已完成',
    4: '已退款'
  }
  return textMap[status] || '未知状态'
}

// 生成支付二维码
const generatePaymentQR = async (order) => {
  try {
    qrCodeLoading.value = true
    qrCodeData.value = null
    qrCodeDialogVisible.value = true
    
    const response = await axios.post(`/api/v1/admin/orders/${order.id}/payment`)
    
    if (response.data.code === 200) {
      qrCodeData.value = {
        ...response.data.data,
        order_no: order.order_no,
        amount: order.amount,
        venue_name: order.venue?.name || '未知场馆',
        reservation_date: order.reservation_date,
        start_time: order.start_time,
        end_time: order.end_time
      }
      ElMessage.success('二维码生成成功')
    } else {
      ElMessage.error(response.data.message || '生成二维码失败')
    }
  } catch (error) {
    console.error('生成二维码失败:', error)
    ElMessage.error('生成二维码失败')
  } finally {
    qrCodeLoading.value = false
  }
}

// 刷新二维码
const refreshQRCode = async () => {
  if (qrCodeData.value) {
    // 重新生成二维码
    const currentOrderId = qrCodeData.value.order_id
    const currentOrder = orders.value.find(o => o.id === currentOrderId)
    if (currentOrder) {
      await generatePaymentQR(currentOrder)
    }
  }
}
</script>

<style scoped>
.order-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: var(--text-primary);
}

.filter-section {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  position: relative;
  overflow: hidden;
}

.stat-card .el-card__body {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: var(--accent-blue);
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: var(--text-secondary);
}

.stat-icon {
  font-size: 32px;
  color: var(--accent-blue);
  opacity: 0.3;
}

.table-section {
  margin-bottom: 20px;
}

.user-info,
.venue-info,
.time-info {
  line-height: 1.4;
}

.user-name,
.venue-name,
.date {
  font-weight: 500;
  color: var(--text-primary);
}

.user-phone,
.venue-location,
.time {
  font-size: 12px;
  color: var(--text-secondary);
  margin-top: 2px;
}

.amount {
  font-weight: 500;
  color: var(--accent-green);
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.order-detail {
  margin: 20px 0;
}

.action-buttons {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
  align-items: center;
}

.activity-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.activity-title {
  font-size: 12px;
  color: var(--text-secondary);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 120px;
}

/* 二维码相关样式 */
.qr-code-container {
  text-align: center;
  padding: 20px 0;
}

.qr-loading {
  padding: 40px 0;
}

.qr-loading .el-icon {
  font-size: 24px;
  margin-bottom: 10px;
}

.qr-code {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.qr-info {
  text-align: left;
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  margin-top: 15px;
}

.qr-info p {
  margin: 8px 0;
  font-size: 14px;
  line-height: 1.5;
}

.qr-tip {
  color: var(--accent-blue);
  font-weight: 500;
  text-align: center;
  margin-top: 15px !important;
  padding-top: 10px;
  border-top: 1px solid #e0e0e0;
}

.qr-error {
  padding: 40px 0;
  color: var(--text-secondary);
}
</style> 